package com.aidong.stadium.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.aidong.activity.biz.MstCampaignBiz;
import com.aidong.jobs.async.SmsTask;
import com.aidong.stadium.biz.MstCoachBiz;
import com.aidong.stadium.biz.MstScheduleBiz;
import com.aidong.stadium.biz.MstStoreBiz;
import com.aidong.stadium.entity.BannerUrl;
import com.aidong.stadium.entity.MstStore;
import com.aidong.stadium.entity.StoreBanner;
import com.aidong.stadium.entity.StoreCourse;
import com.aidong.util.CalendarUtil;
import com.aidong.util.CountDistance;
import com.aidong.util.MyPersonalInfoUtil;
import com.aidong.util.PageUtil;
import com.aidong.util.ReadPropertiesUtil;
import com.aidong.util.SortUtil;
import com.aidong.util.bus.SecurityUtils;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 场馆action
 * 
 * @author java
 * @version 1.0 2015.6.10
 */
@ParentPackage("json")
@Namespace("/")
public class MstStoreAction implements ModelDriven<MstStore> {

	private MstStore mstStore; // 品牌实体类

	@Override
	public MstStore getModel() {
		if (mstStore == null) {
			mstStore = new MstStore();
		}
		return mstStore;
	}

	@Autowired
	private MstStoreBiz mstStoreBiz; // 场馆service
	@Autowired
	private MstScheduleBiz aboutScheduleBiz; // 团操课程service
	@Autowired
	private MstCoachBiz mstCoachBiz; // 私教预约service
	@Autowired
	private MstCampaignBiz mstCampaignBiz; // 活动service
	@Autowired
	SmsTask smsTask;

	private int pageCurrent; // 当前页

	/**
	 * 当前页
	 * 
	 * @param pageCurrent
	 */
	public void setPageCurrent(int pageCurrent) {
		this.pageCurrent = pageCurrent;
	}

	/**
	 * pageCurrent 当前页
	 */

	private Map<String, Object> map; // 返回的json数据

	/**
	 * 返回的json数据
	 * 
	 * @return
	 */
	@JSON
	public Map<String, Object> getMap() {
		return map;
	}

	/**
	 * 门店列表
	 * 
	 * @return
	 */
	@Action(value = "getmststore", results = { @Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String getMstStore() {
		map = new HashMap<String, Object>();
		try {
			Map<String, Object> pageMap = PageUtil.page(50, pageCurrent);
			pageMap.put("brandId", mstStore.getBrandId()); // 品牌ID
			pageMap.put("cityId", mstStore.getCityId()); // 城市ID
			pageMap.put("regionId", mstStore.getRegionId()); // 行政区域ID
			pageMap.put("districtId", mstStore.getDistrictId()); // 商圈ID
			// 门店特色
			int feature = mstStore.getFeature();
			pageMap.put("feature", mstStore.getFeature());
			if (feature > 0) {
				String feaStr = "%" + feature + "%";
				pageMap.put("feaStr", feaStr);
			}

			List<Map<String, Object>> storeMap = mstStoreBiz.getMstStore(pageMap);
			if (storeMap.size() > 0) {
				for (Map<String, Object> store : storeMap) {
					try {
						if (store.get("storeLogo") != null && !"".equals(store.get("storeLogo"))) {
							store.put("storeLogo", ReadPropertiesUtil.getIMGREAD(store.get("storeLogo")));
						} else {
							store.put("storeLogo", "");
						}
						if (store.get("brandLogo") != null && !"".equals(store.get("brandLogo"))) {
							store.put("brandLogo", ReadPropertiesUtil.getIMGREAD(store.get("brandLogo")));
						} else {
							store.put("brandLogo", "");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					String coordinate = store.get("coordinate") + ""; // 场馆所在经纬度
					double lon = mstStore.getLongitude();
					double lat = mstStore.getLatitude();
					if (!"".equals(coordinate) && coordinate != null && lon > 0 && lat > 0) {
						String[] location = coordinate.split(",");
						double discance = CountDistance.distance(lon, lat, Double.parseDouble(location[0]),
								Double.parseDouble(location[1]));
						int dis = (int) Math.rint(discance); // 四舍五入取整数
						int distance = dis / 1000;
						store.put("count", dis);
						if (distance < 1) { // 相距距离 小于一公里显示米 大于一公里显示千米
							if (dis <= 100) {
								store.put("distance", "<100m");
							} else {
								store.put("distance", dis + " m");
							}
						} else {
							store.put("distance", distance + " km");
						}
					} else {
						store.put("count", 0);
					}
					store.remove("coordinate");
				}

				// 按距离排序
				SortUtil.distanceSort(storeMap);
			}
			map.put("code", 1);
			map.put("pageCurrent", pageMap.get("pageCurrent")); // 当前页
			map.put("result", storeMap);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
		return "succ";
	}

	/**
	 * 门店详情 banner图片、服务图标、团操课程预约、私教预约
	 * 
	 * @return
	 */
	@Action(value = "getmststoredetail", results = {
			@Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String getMstStoreDetail() {
		map = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			int storeId = mstStore.getStoreId(); // 门店ID
			if (storeId > 0) {
				// 门店banner
				StoreBanner storeBanner = mstStoreBiz.getMstStoreDetail(storeId);
				Map<String, Object> resultBnner = null;
				if (storeBanner != null) {
					List<BannerUrl> banners = storeBanner.getUrl();
					resultBnner = new HashMap<String, Object>();

					String address = storeBanner.getAddress();
					String phoneNo = storeBanner.getPhoneNo();

					if (!"".equals(address) && address != null) {
						resultBnner.put("address", storeBanner.getAddress());
					} else {
						resultBnner.put("address", "");
					}
					if (!"".equals(phoneNo) && phoneNo != null) {
						resultBnner.put("phoneNo", storeBanner.getPhoneNo());
					} else {
						resultBnner.put("phoneNo", "");
					}
					resultBnner.put("bandLogo", ReadPropertiesUtil.getIMGREAD(storeBanner.getBandLogo()));

					List<Map<String, Object>> bannerList = new ArrayList<Map<String, Object>>();
					if (banners.size() > 0) {
						for (BannerUrl banner : banners) {
							Map<String, Object> bannerMap = new HashMap<String, Object>();
							String bannerUrl = ReadPropertiesUtil.getIMGREAD(banner.getBannerUrl());
							bannerMap.put("bannerUrl", bannerUrl);
							bannerList.add(bannerMap);
						}
					}
					resultBnner.put("url", bannerList);
					resultBnner.put("storeName", storeBanner.getStoreName());
					resultMap.put("banner", resultBnner);
				} else {
					resultMap.put("banner", new StoreBanner());
				}

				// 团操时间安排
				List<Map<String, Object>> dateMap = CalendarUtil.getCalenderWeek();
				Map<String, Object> oneMap = dateMap.get(0);
				String month = oneMap.get("dateDay").toString();// 取得当天的时间
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
				Date monthDate = sdf.parse(month);
				SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
				String mongthStr = sdf2.format(monthDate); // 月
				String week = oneMap.get("week").toString(); // 周

				int weekNum = CalendarUtil.dataConversion(week);
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("storeId", storeId);
				paraMap.put("month", Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()) + mongthStr));
				paraMap.put("week", weekNum);
				paraMap.put("classTime", new SimpleDateFormat("yyyy-MM-dd").format(monthDate));

				// 团操课程预约
				// List<Map<String, Object>> scheduleMap =
				// aboutScheduleBiz.getAboutSchedule(paraMap);
				List<StoreCourse> scheduleMap = aboutScheduleBiz.getAboutSchedule(paraMap);
				for (StoreCourse storeCourse : scheduleMap) {
					storeCourse.setCou(aboutScheduleBiz.getSchedulePerson(storeCourse.getAutoId()));
				}

				// 私教预约
				List<Map<String, Object>> coachMap = mstCoachBiz.getMstCoach(storeId);

				if (coachMap.size() > 0) {
					for (Map<String, Object> coach : coachMap) {
						String photoUrl = ReadPropertiesUtil.getIMGREAD(coach.get("photoUrl")); // 私教照片URL
						coach.put("photoUrl", photoUrl);
						coach.put("count", 0);
						coach.put("distance", "0m");
						double lon = mstStore.getLongitude();
						double lat = mstStore.getLatitude();
						if (!"".equals(coach.get("lat")) && coach.get("lat") != null && !"".equals(coach.get("lon"))
								&& coach.get("lon") != null && lon > 0 && lat > 0) {
							double discance = CountDistance.distance(lon, lat,
									Double.parseDouble(coach.get("lon") + ""),
									Double.parseDouble(coach.get("lat") + ""));
							int dis = (int) Math.rint(discance); // 四舍五入取整数
							int distance = dis / 1000;
							coach.put("count", dis);
							if (distance < 1) { // 相距距离 小于一公里显示米 大于一公里显示千米
								if (dis <= 100) {
									coach.put("distance", "<100m");
								} else {
									coach.put("distance", dis + " m");
								}
							} else {
								coach.put("distance", distance + " km");
							}
						}
					}
				}
				resultMap.put("schedule", scheduleMap);
				resultMap.put("date", dateMap);
				resultMap.put("coach", coachMap);
				map.put("code", 1);
				map.put("result", resultMap);
			} else {
				map.put("code", 0);
				map.put("msg", "缺失参数");
				return "succ";
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
		return "succ";
	}

	/**
	 * 场馆预约体验介绍、可预约时间
	 * 
	 * @return
	 */
	@Action(value = "getstoreappoint", results = { @Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String getStoreAppointDuce() {
		map = new HashMap<String, Object>();
		try {
			int storeId = mstStore.getStoreId(); // 门店ID
			Map<String, Object> resultMap = new HashMap<String, Object>();
			if (storeId > 0) {
				// 门店详情介绍
				Map<String, Object> detailMap = mstStoreBiz.getStoreAppointDuce(storeId);
				detailMap.put("bandLogo", ReadPropertiesUtil.getIMGREAD(detailMap.get("bandLogo")));
				resultMap.put("storeMsg", detailMap);

				// 场馆预约时间排班表
				List<Map<String, Object>> dateMap = CalendarUtil.getCalenderWeek();
				// 场馆不可预约时间排班表
				List<Map<String, Object>> unDateMap = mstStoreBiz.getStoreUnsubscribe(storeId);
				// 不可预约状态
				String sysYear = new SimpleDateFormat("yyyy").format(new Date()); // 系统当前年份
				// 没有不可预约时间
				if (unDateMap.size() == 0) {
					for (Map<String, Object> onday : dateMap) {
						onday.put("appointStatus", 1);
					}
				} else {
					SimpleDateFormat sim = new SimpleDateFormat("M月dd日");
					for (Map<String, Object> onday : dateMap) {
						for (Map<String, Object> unday : unDateMap) {
							String SubDate = onday.get("dateDay").toString(); // 场馆预约排班表(日期)
							if (unday.get("unSubYear").toString().equals(sysYear)) {
								Date unDate = sim.parse(unday.get("unSubDate").toString()); // 不可预约日期
								if (sim.format(unDate).equals(SubDate)) {
									onday.put("appointStatus", 0); // 0、不可约 1、可约
									break;
								} else {
									onday.put("appointStatus", 1);
									break;
								}
							} else {
								onday.put("appointStatus", 1);
								break;
							}
						}
					}
				}
				resultMap.put("appointDate", dateMap);

				map.put("code", 1);
				map.put("result", resultMap);
			} else {
				map.put("code", 0);
				map.put("msg", "参数缺失");
				return "succ";
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
		return "succ";
	}

	/**
	 * 添加场馆预约信息
	 * 
	 * @return
	 */
	@Action(value = "addstadiumappoint", results = {
			@Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String addStadiumAppoint() {
		map = new HashMap<String, Object>();
		try {
			// 解密爱动号
			String idongIdEncrypt = mstStore.getIdongIdEncrypt();
			int idongIdInt = SecurityUtils.decryptIdongId(idongIdEncrypt);
			mstStore.setIdongId(idongIdInt); // 爱动号
			int idongId = mstStore.getIdongId(); // 爱动号
			int storeId = mstStore.getStoreId(); // 门店ID
			String contactName = mstStore.getContactName(); // 联系人姓名
			// 解密联系人电话
			mstStore.setContactPhone(SecurityUtils.decryptPhoneNo(mstStore.getContactPhoneEncrypt()));
			String contactPhone = mstStore.getContactPhone(); // 联系人电话
			int amPm = mstStore.getAmPm(); // 预约上午/下午 1、上午 2、下午
			String shangWu = MyPersonalInfoUtil.dateConversion(amPm);
			String appointDateTime = mstStore.getAppointDateTime(); // 预约时间

			if (storeId > 0 && amPm > 0 && (!"".equals(contactName) && contactName != null)
					&& (!"".equals(contactPhone) && contactPhone != null)
					&& (!"".equals(appointDateTime) && appointDateTime != null)) {

				appointDateTime = CalendarUtil.dateFomat(appointDateTime); // 预约日期
				mstStore.setAppointDateTime(appointDateTime);

				// 场馆信息
				Map<String, Object> remindMap = mstStoreBiz.getStoreAppointRemind(storeId);
				String storeName = remindMap.get("storeName") + ""; // 场馆名
				String remindDate = appointDateTime + " " + shangWu; // 短信提醒预约时间
				String address = remindMap.get("address") + ""; // 场馆地址

				if (idongId > 0) { // 已登陆
					// 当天是否已经预约该场馆
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("storeId", storeId);
					paraMap.put("idongId", idongId);
					paraMap.put("startDate", appointDateTime);
					paraMap.put("pmAm", amPm);
					Map<String, Object> appointMap = mstStoreBiz.getIfAppointStadium(paraMap);
					int appointCount = Integer.parseInt(appointMap.get("count").toString());
					if (appointCount > 0) {// 已预约
						int appointStatus = Integer.parseInt(appointMap.get("status").toString());
						if (appointStatus == 0) {
							map.put("code", 0);
							map.put("msg", "当天您已预约该场馆");
							return "succ";
						} else if (appointStatus == 1) { // 已取消预约，再次预约。修改预约状态
							mstStoreBiz.editStadiumStatus(paraMap);
							smsTask.storeAppointment(contactPhone, storeName, remindDate, address,
									appointMap.get("subscribeId").toString());
							map.put("code", 1);
							map.put("result", "预约成功");
							return "succ";
						}
					} else { // 未预约
						mstStoreBiz.addStadiumAppoint(mstStore);
						smsTask.storeAppointment(contactPhone, storeName, remindDate, address,
								mstStore.getSubscribeId());
						map.put("code", 1);
						map.put("result", "预约成功");
						return "succ";
					}
				} else { // 未登录
					int count = mstCampaignBiz.getIfRegister(contactPhone);
					if (count > 0) { // 已注册
						int rsultIdongId = mstCampaignBiz.getIdongIdByPhone(contactPhone);
						// 当天是否已经预约该场馆
						Map<String, Object> paraMap = new HashMap<String, Object>();
						paraMap.put("storeId", storeId);
						paraMap.put("idongId", rsultIdongId);
						paraMap.put("startDate", appointDateTime);
						paraMap.put("pmAm", amPm);
						Map<String, Object> appointMap = mstStoreBiz.getIfAppointStadium(paraMap);
						int appointCount = Integer.parseInt(appointMap.get("count").toString());
						if (appointCount > 0) { // 已预约
							int appointStatus = Integer.parseInt(appointMap.get("status").toString());
							if (appointStatus == 0) { // 已预约
								map.put("code", 0);
								map.put("msg", "当天您已预约该场馆");
								return "succ";
							} else if (appointStatus == 1) { // 已取消预约，再次预约。修改预约状态
								mstStoreBiz.editStadiumStatus(paraMap);
								smsTask.storeAppointment(contactPhone, storeName, remindDate, address,
										appointMap.get("subscribeId").toString());
								map.put("code", 1);
								map.put("result", "预约成功");
								return "succ";
							}
						} else { // 未预约
									// 保存预约信息
							mstStore.setIdongId(rsultIdongId); // 设置预约爱动号
							mstStoreBiz.addStadiumAppoint(mstStore);
							smsTask.storeAppointment(contactPhone, storeName, remindDate, address,
									mstStore.getSubscribeId());
							map.put("code", 1);
							map.put("result", "预约成功");
							return "succ";
						}
					} else { // 未注册
								// 先注册新用户，产生爱动号
						Map<String, Object> regMap = new HashMap<String, Object>();
						regMap.put("contactName", contactName);
						regMap.put("contactPhone", contactPhone);
						mstCampaignBiz.addMemberReg(regMap);

						// 注册成功后产生爱动号
						int regIdongId = Integer.parseInt(regMap.get("idongId").toString());
						mstStore.setIdongId(regIdongId);
						// 保存预约信息
						mstStoreBiz.addStadiumAppoint(mstStore);
						smsTask.storeAppointment(contactPhone, storeName, remindDate, address,
								mstStore.getSubscribeId());
						map.put("code", 1);
						map.put("msg", "预约成功");
						return "succ";
					}
				}
			} else {
				map.put("code", 0);
				map.put("msg", "参数缺失");
				return "succ";
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
		return null;
	}

	/**
	 * 场馆筛选选项内容
	 * 
	 * @return
	 */
	@Action(value = "getmststoresifting", results = {
			@Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String getMstCityList() {
		map = new HashMap<String, Object>();

		try {
			// 城市列表
			List<Map<String, Object>> citys = mstStoreBiz.getMstCity(mstStore.getAreaId()); // areaId

			// 行政区域列表
			List<Map<String, Object>> regions = new ArrayList<Map<String, Object>>();

			// 热门商圈列表
			Map<String, Object> areas = new HashMap<String, Object>();
			areas.put("areaId", "0");
			areas.put("areaName", "热门商圈");

			// 热门商圈中的热门商圈
			List<Map<String, Object>> dishotMap = new ArrayList<Map<String, Object>>();

			// 热门商圈中的全部商圈
			Map<String, Object> total = new HashMap<String, Object>();
			total.put("areaId", "0");
			total.put("areaName", "全部商圈");
			dishotMap.add(total);

			List<Map<String, Object>> hots = mstStoreBiz.getMstHotDistrict(mstStore.getAreaId());
			for (int i = 0; i < hots.size(); i++) {
				dishotMap.add(hots.get(i));
			}

			areas.put("district", dishotMap);

			regions.add(areas);

			for (Map<String, Object> city : citys) {
				// 区列表
				List<Map<String, Object>> regionList = mstStoreBiz.getMstRegion(city.get("areaId").toString());
				for (Map<String, Object> region : regionList) {
					// 商圈列表
					List<Map<String, Object>> districts = new ArrayList<Map<String, Object>>();

					Map<String, Object> allDis = new HashMap<String, Object>();
					allDis.put("areaId", "0");
					allDis.put("areaName", "全部商圈");
					districts.add(allDis);

					List<Map<String, Object>> listMap = mstStoreBiz.getMstDistrict(region.get("areaId").toString());
					for (int i = 0; i < listMap.size(); i++) {
						districts.add(listMap.get(i));
					}

					region.put("district", districts);
				}
				for (int i = 0; i < regionList.size(); i++) {
					regions.add(regionList.get(i));
				}
			}

			// 品牌列表
			List<Map<String, Object>> brands = new ArrayList<Map<String, Object>>();
			Map<String, Object> brandMap = new HashMap<String, Object>();
			brandMap.put("brandId", 0);
			brandMap.put("chName", "全部品牌");
			brands.add(brandMap);
			Map<String, Object> ma = new HashMap<String, Object>();
			ma.put("cityId", mstStore.getCityId());
			List<Map<String, Object>> mstBrands = mstStoreBiz.getMstBrand(ma);
			for (Map<String, Object> brand : mstBrands) {
				Map<String, Object> brandParaMap = new HashMap<String, Object>();
				brandParaMap.put("brandId", brand.get("brandId"));
				brandParaMap.put("chName", brand.get("chName"));
				brands.add(brandParaMap);
			}

			// 门店特色列表
			List<Map<String, Object>> features = new ArrayList<Map<String, Object>>();
			Map<String, Object> featureMap = new HashMap<String, Object>();
			featureMap.put("code", 0);
			featureMap.put("chName", "全部");
			features.add(featureMap);

			List<Map<String, Object>> feature = mstStoreBiz.getStoreFeature();
			for (Map<String, Object> ture : feature) {
				Map<String, Object> tureParaMap = new HashMap<String, Object>();
				tureParaMap.put("code", ture.get("code"));
				tureParaMap.put("chName", ture.get("chName"));
				features.add(tureParaMap);
			}

			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("regions", regions);
			resultMap.put("brand", brands);
			resultMap.put("feature", features);

			map.put("code", 1);
			map.put("result", resultMap);
			return "succ";
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 0);
			map.put("msg", "系统异常");
			return "succ";
		}
	}
}